import React, { Component } from 'react'
import { debounceTool } from '../assets/tool'

export default function HocApp (Comp) {
    return class Hoc extends Component {
        constructor(props) {
            super(props)
            this.state = { pageScroll: [] } 
        }
        componentDidMount() {
            const { location:{pathname} } = this.props
            const data = JSON.parse(sessionStorage.getItem('pageScroll'))
            if (data && data.length) {  // 本地存储有数据情况
                let list = data.filter(item => item.path === pathname)
                if (list.length) {  // 本地存储存在当前页面数据
                    if (list[0].scroll > 0) document.documentElement.scrollTop = list[0].scroll;
                    this.setState({pageScroll: data})
                } else {    // 本地存储不存在当前页面数据
                    data.push({path: pathname, scroll: 0})
                    this.setState({pageScroll: data})
                }
            } else {    // 本地存储无数据情况
                this.setState({pageScroll: [{path: pathname, scroll: 0}]})
            }

            // 滚动事件调用函数并传值
            document.body.onscroll = debounceTool(() => {
                const scrollTop = document.documentElement.scrollTop
                this.setScrollFn(pathname,scrollTop)
            },100)
        }
        // 页面注销将 state 存储到本地
        componentWillUnmount() {
            const { pageScroll } = this.state
            sessionStorage.setItem('pageScroll', JSON.stringify(pageScroll))
        }
        // 滚动触发事件，将最新滚动值给 state
        setScrollFn = function (page,num) {
            const { pageScroll } = this.state
            const list = pageScroll.map(item => {
                if (item.path !== page) return item;
                item.scroll = num;
                return item;
            })
            this.setState({pageScroll: list})
        }
        render = () => <Comp {...this.props}/>
    }
}
